package data.grammar;

import java.io.IOException;
import java.io.InputStream;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenRewriteStream;

import stream.DebugStream;
import stream.ErrorStream;

import data.Group;

public class LocDataInputStream {
	private final InputStream in;
	private final ErrorStream err;
	private final DebugStream db;
	
	public LocDataInputStream(InputStream in, ErrorStream err, DebugStream db) {
		this.in = in;
		this.err = err;
		this.db = db;
	}
	
	public Group readGroup(String name) throws IOException {
		Group g = new Group(name);
		CharStream input = new ANTLRInputStream(in);
		LocDataLexer lex = new LocDataLexer(input, g);
		final TokenRewriteStream tokens = new TokenRewriteStream(lex);
		LocDataParser p = new LocDataParser(tokens, db, g);
		try {
			p.start();
			int nErrors = lex.getNumberOfSyntaxErrors() + p.getNumberOfSyntaxErrors();
			if (nErrors > 0) {
				throw new IOException("Parse of input stream " + in + " failed with " + nErrors + " syntax errors.");
			}
			return g;
		} catch (RecognitionException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
}
